package com.web.exiaodao.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Function;
import com.web.exiaodao.business.entity.User;
import com.web.exiaodao.business.entity.WalletTradeRecord;
import com.web.exiaodao.business.repository.UserRepository;
import com.web.exiaodao.business.repository.WalletTradeRecordRepository;
import com.web.exiaodao.business.service.WalletTradeRecordService;
import com.web.exiaodao.remote.vo.WalletTradeRecordVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.MyPage;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service("WalletTradeRecordService")
@Transactional(readOnly = false)
public class WalletTradeRecordServiceImpl extends BaseService<WalletTradeRecordVo> implements WalletTradeRecordService {

    private static final Logger LOGGER = Logger.getLogger(WalletTradeRecordServiceImpl.class);

    @Autowired
    private WalletTradeRecordRepository walletTradeRecordRepository;
    @Autowired
    private UserRepository userRepository;

    /**
     * 查询单条WalletTradeRecord信息
     * //@param tId
     *
     * @return 返回单个WalletTradeRecord对象
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<WalletTradeRecordVo> findOne(Long modelId) throws BusinessException {
        WalletTradeRecord obj = new WalletTradeRecord();
        if (modelId != 0) {
            obj = walletTradeRecordRepository.findByIdAndStatusNot(modelId, XaConstant.Status.delete);
        }
        XaResult<WalletTradeRecordVo> xr = new XaResult<>();
        if (XaUtil.isNotEmpty(obj)) {
            xr.setObject(JSON.parseObject(JSON.toJSONString(obj), WalletTradeRecordVo.class));
            LOGGER.info("后台----->查询单个实体----->WalletTradeRecord");
        } else {
            xr.error(XaConstant.Message.object_not_find);
            LOGGER.info(XaConstant.Message.object_not_find);
        }
        return xr;
    }

    /**
     * 分页查询状态非status的WalletTradeRecord数据
     *
     * @param status
     * @param filterParams
     * @param pageable
     * @return 返回对象WalletTradeRecord集合
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<Page<WalletTradeRecordVo>> findListNEStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示非删除的所有数据
            status = XaConstant.Status.delete;
        }
        filters.put("status", new SearchFilter("status", Operator.NE, status));
        Page<WalletTradeRecord> page = walletTradeRecordRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), WalletTradeRecord.class), pageable);
        XaResult<Page<WalletTradeRecordVo>> xr = new XaResult<>();
        xr.setObject(new MyPage<>(page, JSON.parseArray(JSON.toJSONString(page.getContent()), WalletTradeRecordVo.class)));

        //查询用户信息
        if (page.getContent().size() > 0) {
            List<Long> userIdLongs = com.web.webstart.base.util.CollectionUtils.subCollection(page.getContent(), "userId");
            Iterable<User> userIterable = userRepository.findAll(userIdLongs);
            Map<Long, User> userMap = com.web.webstart.base.util.CollectionUtils.listToMap(userIterable.iterator(), new Function<User, Long>() {
                @Override
                public Long apply(User user) {
                    return user.getId();
                }
            });
            for (int i = 0; i < xr.getObject().getContent().size(); ++i) {
                WalletTradeRecordVo vo = xr.getObject().getContent().get(i);
                User userTemp = userMap.get(vo.getUserId());
                xr.getObject().getContent().get(i).setUser(userTemp);
            }
        }

        LOGGER.info("后台----->分页查询实体集合（状态不等于）----->WalletTradeRecord");
        return xr;
    }

    /**
     * 分页查询状态status的WalletTradeRecord数据
     *
     * @param status
     * @param filterParams
     * @param pageable
     * @return 返回对象WalletTradeRecord集合
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<Page<WalletTradeRecordVo>> findListEQStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示正常数据
            status = XaConstant.Status.valid;
        }
        filters.put("status", new SearchFilter("status", Operator.EQ, status));
        Page<WalletTradeRecord> page = walletTradeRecordRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), WalletTradeRecord.class), pageable);
        XaResult<Page<WalletTradeRecordVo>> xr = new XaResult<>();
        xr.setObject(new MyPage<>(page, JSON.parseArray(JSON.toJSONString(page.getContent()), WalletTradeRecordVo.class)));
        LOGGER.info("后台----->分页查询实体集合（状态等于）----->WalletTradeRecord");
        return xr;
    }
    /**
     * 保存WalletTradeRecord信息
     *
     * @param model
     * @return
     * @throws BusinessException
     */
    @Transactional(rollbackFor = Exception.class)
    public XaResult<WalletTradeRecordVo> saveOrUpdate(WalletTradeRecordVo model) throws BusinessException {
        WalletTradeRecord obj = null;
        if (XaUtil.isNotEmpty(model.getId())) {
            obj = walletTradeRecordRepository.findOne(model.getId());
        } else {
            obj = new WalletTradeRecord();
        }
        obj.setCreateUser(XaUtil.isNotEmpty(model.getCreateUser()) ? model.getCreateUser() : obj.getCreateUser());
        obj.setUserId(XaUtil.isNotEmpty(model.getUserId()) ? model.getUserId() : obj.getUserId());
        obj.setMoney(XaUtil.isNotEmpty(model.getMoney()) ? model.getMoney() : obj.getMoney());
        obj.setTradeType(XaUtil.isNotEmpty(model.getTradeType()) ? model.getTradeType() : obj.getTradeType());
        obj.setIncomeExpendType(XaUtil.isNotEmpty(model.getIncomeExpendType()) ? model.getIncomeExpendType() : obj.getIncomeExpendType());
        obj.setIncomeExpendMethod(XaUtil.isNotEmpty(model.getIncomeExpendMethod()) ? model.getIncomeExpendMethod() : obj.getIncomeExpendMethod());
        obj.setRemarks(XaUtil.isNotEmpty(model.getRemarks()) ? model.getRemarks() : obj.getRemarks());
        obj.setTradeOrderNo(XaUtil.isNotEmpty(model.getTradeOrderNo()) ? model.getTradeOrderNo() : obj.getTradeOrderNo());
        obj.setTradeStatus(XaUtil.isNotEmpty(model.getTradeStatus()) ? model.getTradeStatus() : obj.getTradeStatus());
        obj.setAccountBalance(XaUtil.isNotEmpty(model.getAccountBalance()) ? model.getAccountBalance() : obj.getAccountBalance());
        obj.setTradeCloseDateTime(XaUtil.isNotEmpty(model.getTradeCloseDateTime()) ? model.getTradeCloseDateTime() : obj.getTradeCloseDateTime());
        obj = walletTradeRecordRepository.save(obj);
        XaResult<WalletTradeRecordVo> xr = new XaResult<>();
        xr.setObject(JSON.parseObject(JSON.toJSONString(obj), WalletTradeRecordVo.class));
        LOGGER.info("后台新增或编辑数据成功！");
        return xr;
    }

    /**
     * 修改WalletTradeRecord状态，可一次修改多条   3删除  -1锁定  1正常
     * //@param userId
     *
     * @param modelIds
     * @param status
     * @return 返回WalletTradeRecord对象
     * @throws BusinessException
     */
    @Transactional(rollbackFor = Exception.class)
    public XaResult<WalletTradeRecordVo> multiOperate(
            String modelIds, Integer status) throws BusinessException {
        XaResult<WalletTradeRecordVo> xr = new XaResult<>();
        if (status == null) {
            status = XaConstant.Status.delete;
        }
        if (modelIds != null) {
            String[] ids = modelIds.split(",");
            for (String id : ids) {
                WalletTradeRecord obj = walletTradeRecordRepository.findByIdAndStatusNot(Long.parseLong(id), status);
                if (XaUtil.isNotEmpty(obj)) {
                    obj.setStatus(status);
                    obj = walletTradeRecordRepository.save(obj);
                }
            }
        }
        LOGGER.info("批量修改数据状态成功！");
        return xr;
    }

}
